package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.heima.wemedia.constants.MqConstants.*;

/**
 * @author Psycho
 * @create 2022-04-25-18:44
 */
@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    //将Mapper注入进行批量操作
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private RabbitTemplate rabbitTemplate;



    /**
     * 查询文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listNews(WmNewsPageReqDto dto) {
        //分页的数据前处理
        dto.checkParam();
        //构建查询对象
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        //文章状态的指定
        if(dto.getStatus()!=null){      //  ==null即为查全部
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //关键字的模糊查询
        if(StringUtils.isNotBlank(dto.getKeyword())){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //频道的查询
        if(dto.getChannelId()!=null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //发行的时间段之间
        if(dto.getBeginPubDate() !=null&&dto.getEndPubDate() !=null){
            queryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        //按照时间的倒叙排序
        queryWrapper.orderByDesc(WmNews::getPublishTime);
        //数据进行分页
        IPage page = new Page(dto.getPage(),dto.getSize());
        page = page(page,queryWrapper);
        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 新增或者修改一篇文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult insertOrUpdateOneNews(WmNewsDto dto) {
        //0.条件判断
        if(Objects.isNull(dto)||dto.getContent()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //1.保存或修改文章
        WmNews wmNews = new WmNews();
        //对象间相同类型，相同名称的属性注入
        BeanUtils.copyProperties(dto,wmNews);
        //其他属性手动注入
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setPublishTime(new Date());
        //如果当前封面类型为自动 -1
        if(dto.getType() == WemediaConstants.WM_NEWS_TYPE_AUTO){
            //该字段不能为负数
            wmNews.setType(null);
        }
        //封面图片  list---> string
        if(!Objects.isNull(dto.getImages())&&dto.getImages().size()>0){
            String images = dto.getImages().stream().collect(Collectors.joining(","));
            wmNews.setImages(images);
        }

        save(wmNews);

        //2.判断是否为草稿  如果为草稿结束当前方法
        if(dto.getStatus()==WemediaConstants.WM_CONTENT_REFERENCE){
            return ResponseResult.okResult(wmNews);
        }

        //3.不是草稿，保存文章内容图片与素材的关系
        //遍历出内容中的图片路径集合
        List<String> imagesPath = ectractUrlInfo(dto);
        if(imagesPath != null&& imagesPath.size()>0){
            saveRelativeInfoForContent(wmNews, imagesPath);
        }
        //4.不是草稿，保存文章封面图片与素材的关系，如果当前布局是自动，需要匹配封面图片
        //判断是不是自动
        List<String> images = dto.getImages();
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            if(imagesPath.size()>=1 && imagesPath.size() < 3){
                //单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = imagesPath.stream().limit(1).collect(Collectors.toList());
            }else if(imagesPath.size()>=3){
                //多图
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = imagesPath.stream().limit(3).collect(Collectors.toList());
            }else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            //修改文章
            if(images != null && images.size() > 0){
                wmNews.setImages(StringUtils.join(images,","));
            }
            updateById(wmNews);
        }
        if(images != null && images.size() > 0){
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
        }
        //进行文章的审核
        //wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        //通过MQ进行延时消息的发布
        rabbitTemplate.convertAndSend(HMALL_TTL_DIRECT, HMALL_TTL_KEY, wmNews.getId(), message -> {
            MessageProperties messageProperties = message.getMessageProperties();
            messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            //设置消息存活时间为10秒
            long liveTime = dto.getPublishTime().getTime() - new Date().getTime();
            if(liveTime<0){
                liveTime = 1;
            }
            messageProperties.setExpiration(String.valueOf(liveTime));
            return message;
        });


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private KafkaTemplate<String,Object> kafkaTemplate;

    /**
     * 文章上下架功能
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //对数据的检验
        if(dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否已发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //修改上下架
            if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
            lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()).update();
        }

        //处理发消息的数据
        if(wmNews.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Map<String,Object> map = new HashMap();
        map.put("articleId",wmNews.getArticleId());
        map.put("enable",dto.getEnable());
        //发送消息给Article
        kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void saveRelativeInfoForContent(WmNews wmNews, List<String> imagesPath) {
        saveRelativeInfo(imagesPath,wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);
    }

    private void saveRelativeInfo(List<String> imagesPath, Integer id, Short wmContentReference) {
        //通过拥有的图片路径集合查询material_id集合
        //通过图片的url查询存有相同路径的WmMaterial对象
        List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imagesPath));
        //对查询出来的数组进行长度判断，如果不等于图片数组的集合长度说明图片出现问题
        //判断素材是否有效
        if(dbMaterials==null || dbMaterials.size() == 0){
            //手动抛出异常   第一个功能：能够提示调用者素材失效了，第二个功能，进行数据的回滚
            throw new CustomException(AppHttpCodeEnum.NEED_ADMIND);
        }
//        if(dbMaterials.size() != dbMaterials.size()){
//            throw new CustomException(AppHttpCodeEnum.NEED_ADMIND);
//        }
        //相等的话就行进material_id的提取
        List<Integer> materialIds = dbMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
        wmNewsMaterialMapper.saveRelations(materialIds, id,wmContentReference);
    }


    private List<String> ectractUrlInfo(WmNewsDto dto) {
        //获取content的值
        String content = dto.getContent();
        //转化成JSON数组
        List<Map> list = JSON.parseArray(content, Map.class);
        //遍历出文章中的图片地址并保存起来
        List<String> images = new ArrayList<>(list.size());
        for (Map map : list) {
            if("image".equals(map.get("type"))){
                String imagePath = (String) map.get("value");
                images.add(imagePath);
            }
        }
        return images;
    }
}
